package swu.edu.cn.javaee.service;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import swu.edu.cn.javaee.entity.Gmember;
import swu.edu.cn.javaee.entity.GmemberInfo;
import swu.edu.cn.javaee.mapper.GmemberMapper;
import static swu.edu.cn.javaee.component.Signal.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GmemberService {
    @Resource
    private GmemberMapper gmemberMapper;



    //用户加群
    public String saveGmember(String gid,String uid,String gnickname){
        Gmember gmember=new Gmember();
        Date join_time=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Gmember result=gmemberMapper.queryMemberById(uid,gid);
        if (result==null){
            gmember.setGid(gid);
            gmember.setUid(uid);
            gmember.setGnickname(gnickname);
            gmember.setJoin_time(format.format(join_time));
            gmemberMapper.saveGmember(gmember);
            System.out.println(gmember);
            return SUCCESS_CODE;
        }
        else {
            return FAILED_CODE_MEMBER_EXIST;
        }
    }

    //显示本群全体群成员
    public GmemberInfo queryGmemberList(String gid){
        List<Gmember> gmemberList=gmemberMapper.queryGmemberList(gid);
        GmemberInfo gmemberInfo= new GmemberInfo();
        Integer counts=gmemberMapper.counts(gid);
        if (gmemberList.size()!=0){
            gmemberInfo.setCode("0");
            gmemberInfo.setMsg("");
            gmemberInfo.setCount(String.valueOf(counts));
            gmemberInfo.setData(gmemberList);
            System.out.println(gmemberInfo);
            return gmemberInfo;
        }
        else {
            return null;
        }
    }

    //根据id查找群员
    public Gmember queryMemberById(String uid,String gid){
        Gmember gmember=gmemberMapper.queryMemberById(uid,gid);
        if (gmember!=null){
            System.out.println(gmember);
            return gmember;
        }
        else {
            return null;
        }
    }

    //删除群成员
    public String deleteMember(String uid,String gid){
        Gmember result=gmemberMapper.queryMemberById(uid, gid);
        if (result!=null){
            gmemberMapper.deleteMember(result);
            return SUCCESS_CODE;
        }
        else {
            return FAILED_CODE_MEMBER_NO_EXIST;
        }
    }
}
